package com.gec.mall.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gec.mall.pojo.TbUser;
import com.gec.mall.security.utils.CommonResult;
import com.gec.mall.security.utils.JwtTokenUtil;
import com.gec.mall.security.utils.UserDetailImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @Author: li
 * @Date: 2023/2/17
 * @PACKAGE_NAME:com.gec.security.filter
 * @Project_Name:Javademo
 * @VERSION: 1.0.0
 */
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JwtAuthenticationFilter(String url, AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        //指定用户认证的url
        setFilterProcessesUrl(url);
    }

    //用户认证方法
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //shiro  subject   subject.login( token )  token(username,paassword)
        //获取前端json数据（账号与密码）
        try {
            TbUser user = new ObjectMapper().readValue(request.getInputStream(), TbUser.class);
            System.out.println("请求的认证的账号: " + user.getUsername());
            System.out.println("请求认证的密码:" + user.getPassword());
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(null, null, new ArrayList<>()));
        }

    }

    //成功认证的回调方法，返回jwt回客户端
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        //获取认证的主体信息
        UserDetailImpl userDetail = (UserDetailImpl) authResult.getPrincipal();

        String token = JwtTokenUtil.createToken("gec",userDetail.getUsername(), 1800l);
        System.out.println("创建了Jwt : " + token);
        out.write(new ObjectMapper().writeValueAsString(CommonResult.success(JwtTokenUtil.TOKEN_PREFIX+token)));
        out.flush();
        out.close();
    }

    //认证失败后的回调方法
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(CommonResult.failed("登录失败")));
        out.flush();
        out.close();
    }
}
